package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.behavior.mapper.ApLikesBehaviorMapper;
import com.usian.behavior.mapper.BehaviorEntryMapper;
import com.usian.behavior.service.LikeBehaviorService;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.behavior.dtos.LikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApLikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LikeBehaviorServiceImpl extends BaseServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements LikeBehaviorService {
    @Autowired
    private BehaviorEntryMapper entryMapper;
    @Override
    public ResponseResult likeOpr(LikesBehaviorDto dto) {
        if (dto == null || dto.getArticleId() == null || dto.getOperation() == null || (dto.getOperation() != 0 && dto.getOperation() !=1))return paramError;
        Integer userId = ThreadLocalUtils.getUserId();
        if (userId == null)return needLogin;
        ApBehaviorEntry behaviorEntry = entryMapper.selectOne(Wrappers.<ApBehaviorEntry>lambdaQuery().eq(ApBehaviorEntry::getEntryId, userId).select(ApBehaviorEntry::getId));
        ApLikesBehavior likesBehavior = getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getEntryId, behaviorEntry.getId()).eq(ApLikesBehavior::getArticleId, dto.getArticleId()));
        if (likesBehavior == null){//从未点过赞
            likesBehavior = new ApLikesBehavior();
            likesBehavior.setOperation(dto.getOperation());
            likesBehavior.setType(dto.getType());
            likesBehavior.setCreatedTime(new Date());
            likesBehavior.setEntryId(behaviorEntry.getId());
            likesBehavior.setArticleId(dto.getArticleId());
            save(likesBehavior);
        }else {
            likesBehavior.setOperation(dto.getOperation());
            updateById(likesBehavior);
        }
        return success;
    }

    @Override
    public Boolean getLikeStatus(Integer userId, Long articleId) {
        if (userId == null || articleId == null)return false;
        Integer entryId = entryMapper.selectOne(Wrappers.<ApBehaviorEntry>lambdaQuery().eq(ApBehaviorEntry::getEntryId, userId)).getId();
        ApLikesBehavior like = getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getEntryId, entryId).eq(ApLikesBehavior::getArticleId, articleId));
        return like != null && like.getOperation() == 0;
    }
}
